package com.songhq.zonghe.work;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Component;

@Component
public class WorkThreadPoolExcutor {

	private int corePoolSize = 3;

	private int MaxnumPoolSize = 5;

	private int keepAliveTime = 20;

	private ThreadPoolExecutor workers;

	private int QueueSize = 2;

	private void init() {
		//列队的特性是先进先出
		LinkedBlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<Runnable>(QueueSize);

		/*
		 * 四中拒绝策略 new ThreadPoolExecutor.AbortPolicy(); 抛异常 new
		 * ThreadPoolExecutor.CallerRunsPolicy(); 在caller线程里执行 new
		 * ThreadPoolExecutor.DiscardPolicy(); 忽略后进来的任务，执行先进来的任务 new
		 * ThreadPoolExecutor.DiscardOldestPolicy();
		 */ // 忽略先在列队了任务，最后进列队的任务执行
		// 自定义拒绝策略
		RejectedExecutionHandler handler = new RejectedExecutionHandler() {
			@Override
			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

				System.out.println("什么也没做，放弃任务 " + r.toString());

				/*if (!executor.isShutdown()) {
					r.run();// 当前线程执行任务
				}*/
			}
		};
		workers = new ThreadPoolExecutor(corePoolSize, MaxnumPoolSize, keepAliveTime, TimeUnit.SECONDS,
				linkedBlockingQueue, handler);

	}
	public void doWork(Runnable runnable){
		if(workers==null){
			init();
		}
		//提交了一个没有返回值的任务，会new一个Thread 执行
		workers.execute(runnable);
		/*Callable<String> callable = new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(3000);
				return "callable有数据返回了";
			}
		};*/
		//lambda表达式的写法，submit（）提交一个任务也是会new 出一个thread去执行
	    Future<String> future = workers.submit(()->{Thread.sleep(3000);
	    return "callable有数据返回了";});
	    long a=System.currentTimeMillis();
	    try {
	    	//future当前线程会阻塞，获取另外一个线程执行的结果
			String string = future.get();
			 long b=System.currentTimeMillis();
			 
			 System.out.println("future.get()"+string+"阻塞了"+(b-a));
			
			
		} catch (InterruptedException | ExecutionException e) {
			
			e.printStackTrace();
		}
	    //另一种方式提交Callable
	    FutureTask<String> futureTask =
	    		   new FutureTask<String>(new Callable<String>() {
	    		    public String call() {
	    		    	
	    		       return "futureTask有数据返回了";
	    		   }});
	    		  
	    workers.execute(futureTask);
	    
	    try {
			String futureString = futureTask.get();
			System.out.println("futureTask.get()"+futureString+"阻塞了");
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	    
	    
	    
	}
}